import 'package:flutter/material.dart';
import 'package:markdown_widget/markdown_widget.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

class PrivacyPolicyPage extends StatefulWidget {
  final bool showAgreement;

  const PrivacyPolicyPage({super.key, this.showAgreement = false});

  @override
  State<PrivacyPolicyPage> createState() => _PrivacyPolicyPageState();
}

class _PrivacyPolicyPageState extends State<PrivacyPolicyPage> {
  String? _mdData;
  bool _loading = true;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _loadMarkdown();
  }

  Future<void> _loadMarkdown() async {
    final locale = Localizations.localeOf(context).languageCode;
    final assetPath = 'assets/privacy/${locale == 'zh' ? 'zh' : 'en'}.md';
    final data = await DefaultAssetBundle.of(context).loadString(assetPath);
    setState(() {
      _mdData = data;
      _loading = false;
    });
    if (widget.showAgreement) _showAgreementDialog();
  }

  void _showAgreementDialog() {
    showDialog(
      context: context,
      builder: (_) => AlertDialog(
        title: Text(AppLocalizations.of(context)!.privacyPolicyTitle),
        content: Text(AppLocalizations.of(context)!.privacyPolicyAgreeMessage),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              Navigator.pop(context, false);
            },
            child: Text(AppLocalizations.of(context)!.privacyPolicyDisagree),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(context);
              Navigator.pop(context, true);
            },
            child: Text(AppLocalizations.of(context)!.privacyPolicyAgree),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context)!;
    return Scaffold(
      appBar: AppBar(title: Text(l10n.profileTitle)),
      body: _loading
          ? const Center(child: CircularProgressIndicator())
          : MarkdownWidget(
              data: _mdData ?? '',
              config: MarkdownConfig.darkConfig.copy(configs: [
                LinkConfig(
                  onTap: (url) async {
                    if (await canLaunchUrl(Uri.parse(url))) {
                      await launchUrl(Uri.parse(url),
                          mode: LaunchMode.externalApplication);
                    }
                  },
                ),
              ]),
            ),
    );
  }
}
